package main

import (
	"context"
	"github.com/spf13/viper"
	"go-demo-2025/common"
	"go-demo-2025/router"
	"go-demo-2025/service/message_queue/kafka_demo1/consume_sync"
	"go-demo-2025/service/message_queue/kafka_demo1/local_message"
	"go-demo-2025/utils/kafkaUtil"
	"go-demo-2025/utils/redisUtil"
	"log"
)

// 用下面的编译命令即可编译出针对linux系统的二进制文件
// GOOS=linux GOARCH=amd64 go build main.go
func main() {
	common.InitConfig()   //配置初始化
	common.InitDB()       //数据库初始化 (只初始化一次)
	redisUtil.InitRedis() //Redis初始化

	// sql db 初始化
	if err := common.InitSqlDB(); err != nil {
		panic(err)
	}
	defer common.CloseSqlDB()

	// Kafka 初始化
	if err := kafkaUtil.InitKafka(); err != nil {
		panic(err)
	}
	defer kafkaUtil.CloseKafka()

	// 生产者方式1: 启动kafka重试任务(本地消息表方案)
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	go local_message.StartMessageRetryTask(ctx)

	// 生产者方式2: 初始化回查服务(通过 “准备 - 提交” 两阶段模式实现消息回查机制，确保业务成功后才投递消息)
	/*
		if err := check_message_back.InitLookbackService(); err != nil {
			panic(fmt.Sprintf("回查服务初始化失败: %v", err))
		}
		go check_message_back.StartLookbackService(ctx) // 启动回查服务协程
	*/

	// 消费者方式1: 启动同步消费者
	ctx, cancel = context.WithCancel(context.Background())
	defer cancel()
	go func() {
		if err := consume_sync.StartSyncConsumer(ctx, "order_events"); err != nil {
			log.Printf("同步消费者异常退出: %v\n", err)
		}
	}()

	// 消费者方式2: 启动异步消费者
	/*
		asyncConsumer := consume_async.NewAsyncConsumer("order_events")
		go func() {
			if err := asyncConsumer.Start(); err != nil {
				log.Printf("异步消费者异常退出: %v\n", err)
			}
		}()
		defer asyncConsumer.Stop()
	*/

	//路由初始化
	r := router.Router()
	router.CustomerRouter(r)
	router.OrderRouter(r)
	router.UserRouter(r)

	router.KafkaDemoRouter(r)

	//服务端口
	port := viper.GetString("server.port")
	if port != "" {
		r.Run(":" + port) //加载 conf/application.yml 中 server.port
	} else {
		r.Run() //如果不指定IP地址、端口号，默认为本机IP地址、8080端口
	}
}
